<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Services\JWTService;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Contract\RequestInterface;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Util\JWTUtil;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class Auth implements MiddlewareInterface
{
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    //鉴权处理
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $token = $this->request->getHeaderLine('Authorization');
        if (empty($token)) {
            return $this->response->json([
                'code' => 401,
                'msg' => '请先登录'
            ]);
        }
        $data = JWTService::decode($token);
        if (!$data) {
            return $this->response->json(
                [
                    'code' => 401,
                    'data' => [
                        'error' => '登录失效，请重新登录',
                    ],
                ]
            );
        }
        $this->request->user = $data;
        //验证通过
        return $handler->handle($request);
    }
}
